package com.example.springbootdemo.framework.shrio;

import com.example.springbootdemo.framework.shrio.service.ShiroService;
import com.example.springbootdemo.module.user.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private ShiroService ShiroService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        Set<String> menuPermissions;
        Set<String> roles;

        if (ShiroService.checkAdmin(user.getUserId())) {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        }else{
            roles = ShiroService.selectRoleKeys(user.getUserId());
            menuPermissions = ShiroService.selectPermsByUserId(user.getUserId());
            // 角色加入AuthorizationInfo认证对象
            info.setRoles(roles);
            // 权限加入AuthorizationInfo认证对象
            info.setStringPermissions(menuPermissions);
        }

        System.out.println("授权");
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // String usename = (String) authenticationToken.getPrincipal();
        //  String password = (String) authenticationToken.getCredentials();
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String loginName = upToken.getUsername();
        User user = ShiroService.findPassByLoginName(loginName);
        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        } else if (user.getStatus().equals("1")) {
            throw new DisabledAccountException("账号已停用");
        } else {
            if (!matches(user, String.valueOf(upToken.getPassword())))
                throw new IncorrectCredentialsException("密码错误");
        }

        AuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, upToken.getPassword(), getName());//认证通过后，存放在session,一般存放user对//用户数据库中的密码//返回Realm名
        return simpleAuthenticationInfo;
    }

    public boolean matches(User user, String newPassword) {

        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
    }

    public String encryptPassword(String username, String password, String salt) {
        return new Md5Hash(username + password + salt).toHex().toString();
    }

    /**
     * 清理缓存权限【可能无效】
     */
    public void clearCachedAuthorizationInfo() {

        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

}
